package cn.bocweb.spinning.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.GetQaCtypeBean;
import cn.bocweb.spinning.model.Bean.ItemBean;
import cn.bocweb.spinning.model.Bean.QaListBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.activity.LoginAcivity;
import cn.bocweb.spinning.view.activity.MainActivity;
import cn.bocweb.spinning.view.activity.MyAnswerActivity;
import cn.bocweb.spinning.view.activity.MyQuestionActivity;
import cn.bocweb.spinning.view.activity.QuestionDetailActivity;
import cn.bocweb.spinning.view.activity.WriteAnswerActivity;
import cn.bocweb.spinning.view.activity.WriteQuestionActivity;
import cn.bocweb.spinning.view.adapter.QaItemAdapter;
import cn.bocweb.spinning.view.adapter.QuestionListAdapter;
import cn.bocweb.spinning.view.common.SwipeRefreshHelper;
import cn.bocweb.spinning.view.dialog.ItemDialog;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 16/8/19.
 */
public class QuestionListFragment extends Fragment implements View.OnClickListener, SwipeRefreshHelper.OnSwipeRefreshListener {

    QaItemAdapter qaItemAdapter;
    QuestionListAdapter questionListAdapter;
    List<QaListBean.DataBean> list;
    UserPresenter mPresenter;
    List<GetQaCtypeBean.DataEntity> mDataEntityList;
    int page = 1;
    boolean isLastPage = false;
    SwipeRefreshHelper mSwipeRefreshHelper;
    String cat = "all";
    MainActivity main;
    String userid = "";
    boolean hasShown;
    UserBean.DataEntity dataEntity;

    List<ItemBean> itemBeanList;
    ItemDialog itemDialog;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.question_list_tips)
    RecyclerView questionListTips;
    @Bind(R.id.question_list_content)
    ListView questionListContent;
    @Bind(R.id.ques_refresh)
    SwipeRefreshLayout quesRefresh;
    @Bind(R.id.imageview_select)
    ImageView imageviewSelect;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.activity_question_list, container, false);
        ButterKnife.bind(this, view);
        main = (MainActivity) getActivity();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        setHasOptionsMenu(true);
        dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(getContext());
        userid = dataEntity.getUserid();

        itemBeanList = new ArrayList<>();
        itemDialog = new ItemDialog(getContext(), itemBeanList);
        itemDialog.setOnConfirmListener(new ItemDialog.OnConfirmListener() {
            @Override
            public void onClick(int confirm, String id) {
                qaItemAdapter.setSelection(confirm);
                qaItemAdapter.notifyDataSetChanged();
                itemDialog.setConfirmed(confirm);
                hasShown = false;
                list.clear();
                questionListAdapter.notifyDataSetChanged();
                cat = id;
                page = 1;
                isLastPage = false;
                mPresenter.qaList(page, cat);
            }
        });

        mPresenter = new UserPresenterImp();
        list = new ArrayList<>();
        questionListAdapter = new QuestionListAdapter(getContext(), list);
        mDataEntityList = new ArrayList<>();
        qaItemAdapter = new QaItemAdapter(mDataEntityList);
        mSwipeRefreshHelper = new SwipeRefreshHelper(quesRefresh, questionListContent, this);

        initTips();
        initClick();
        initToolbar();
        initListView();

        mPresenter.qaappGetCat();

        questionListAdapter.setOnAnswerListener(new QuestionListAdapter.OnAnswerListener() {
            @Override
            public void answer(String id, int reply) {
                Intent intent = new Intent(getContext(), WriteAnswerActivity.class);
                intent.putExtra(Constant.TO_QUES_DETAIL_ANSWER, id);
                intent.putExtra(Constant.TO_QUES_DETAIL_ANSWER_NUM, reply);
                startActivityForResult(intent, Constant.QUES_DETAIL_BACK_QUES_LIST);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(GetQaCtypeBean bean) {
        if (bean.getReturn_code() == 0) {
            GetQaCtypeBean.DataEntity dataEntity = new GetQaCtypeBean.DataEntity();
            dataEntity.setId("all");
            dataEntity.setTitle("全部");

            ItemBean itemBean1 = new ItemBean();
            itemBean1.setId("all");
            itemBean1.setTitle("全部");
            itemBeanList.add(itemBean1);

            for (GetQaCtypeBean.DataEntity dataEntity1 : bean.getData()) {
                ItemBean itemBean = new ItemBean();
                itemBean.setId(dataEntity1.getId());
                itemBean.setTitle(dataEntity1.getTitle());
                itemBeanList.add(itemBean);
            }

            mDataEntityList.add(0, dataEntity);
            mDataEntityList.addAll(bean.getData());
            qaItemAdapter.setSelection(0);
            qaItemAdapter.notifyDataSetChanged();
            mPresenter.qaList(page, "all");
        }
    }

    public void onEventMainThread(QaListBean bean) {
        if (quesRefresh.isRefreshing()) {
            quesRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            list.addAll(bean.getData());
            questionListAdapter.notifyDataSetChanged();
        } else if (bean.getReturn_code() == -201) {
            isLastPage = true;
            DeviceUtil.MyToast(getContext(), "已经是最后一页");
        } else {
            DeviceUtil.MyToast(getContext(), bean.getMsg());
        }
    }

    private void initListView() {

        questionListContent.setAdapter(questionListAdapter);
        questionListContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getContext(), QuestionDetailActivity.class);
                intent.putExtra(Constant.TO_QA_DETAIL, list.get(position).getId());
                startActivityForResult(intent, Constant.QUES_DETAIL_BACK_QUES_LIST);
            }
        });


    }

    private void initTips() {

        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        questionListTips.setAdapter(qaItemAdapter);
        questionListTips.setLayoutManager(manager);
        qaItemAdapter.setOnItemClickListener(new QaItemAdapter.OnItemClickListener() {

            @Override
            public void onClick(int position, String id) {
                qaItemAdapter.setSelection(position);
                qaItemAdapter.notifyDataSetChanged();
                itemDialog.setConfirmed(position);
                hasShown = false;
                list.clear();
                questionListAdapter.notifyDataSetChanged();
                cat = id;
                page = 1;
                isLastPage = false;
                mPresenter.qaList(page, cat);
            }
        });
    }

    private void initToolbar() {
        toolbar.setTitle("切磋");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        main.setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent;
                dataEntity.readInfoFromLocal(getContext());
                if (TextUtils.isEmpty(dataEntity.getUserid())) {
                    intent = new Intent(getContext(), LoginAcivity.class);
                    startActivity(intent);
                } else {
                    switch (item.getItemId()) {
                        case R.id.send_question: {
                            intent = new Intent(getContext(), WriteQuestionActivity.class);
                            startActivity(intent);
                            break;
                        }
                        case R.id.my_question: {
                            intent = new Intent(getContext(), MyQuestionActivity.class);
                            startActivity(intent);
                            break;
                        }
                        case R.id.my_answer: {
                            intent = new Intent(getContext(), MyAnswerActivity.class);
                            startActivity(intent);
                            break;
                        }
                    }
                }
                return false;
            }
        });


    }

    private void initClick() {
        imageviewSelect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageview_select:
                itemDialog.show();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onRefresh() {
        page = 1;
        isLastPage = false;
        hasShown = false;
        list.clear();
        questionListAdapter.notifyDataSetChanged();
        mPresenter.qaList(page, cat);
    }

    @Override
    public void onLoad() {
        if (!isLastPage) {
            page++;
            mPresenter.qaList(page, cat);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
